﻿
using UnityEngine;

/// <summary>
/// Tween the widget's size.
/// </summary>

[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("UGUI/Tween/Tween Width")]
public class UGUITweenWidth : UGUITweener
{
    public override object fromValue { get { return from; } set { from = (int)value; } }
    public override object toValue { get { return to; } set { to = (int)value; } }

    public int from = 100;
	public int to = 100;
	public bool updateTable = false;

    RectTransform mWidget;

    public RectTransform cachedWidget { get { if (mWidget == null) mWidget = GetComponent<RectTransform>(); return mWidget; } }

    /// <summary>
    /// Tween's current value.
    /// </summary>
    public int value
    {
        get
        {
            return (int)cachedWidget.sizeDelta.x;
        }
        set
        {
            var sizeDelta = cachedWidget.sizeDelta;
            sizeDelta.x = value;

            cachedWidget.sizeDelta = sizeDelta;
        }
    }

    /// <summary>
    /// Tween the value.
    /// </summary>
    protected override void OnUpdate (float factor, bool isFinished)
	{
		value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
	}

	/// <summary>
	/// Start the tweening operation.
	/// </summary>

	static public UGUITweenWidth Begin (RectTransform widget, float duration, int width)
	{
        UGUITweenWidth comp = UGUITweener.Begin<UGUITweenWidth>(widget.gameObject, duration);
		comp.from = (int)widget.sizeDelta.x;
		comp.to = width;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}
		return comp;
	}

	[ContextMenu("Set 'From' to current value")]
	public override void SetStartToCurrentValue () { from = value; }

	[ContextMenu("Set 'To' to current value")]
	public override void SetEndToCurrentValue () { to = value; }

	[ContextMenu("Assume value of 'From'")]
	void SetCurrentValueToStart () { value = from; }

	[ContextMenu("Assume value of 'To'")]
	void SetCurrentValueToEnd () { value = to; }
}
